/*
 * Copyright (c) 2006-2018, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020-8-31      Rice   first version
 */

#include <rtthread.h>
#include <rtdevice.h>
#include "board.h"

#ifdef RT_USING_SPI

#if defined(BSP_USING_SPI1) || defined(BSP_USING_SPI2) || defined(BSP_USING_SPI3) || defined(BSP_USING_SPI4)

#include "drv_spi.h"
#include "spi_config.h"
#include <string.h>
#include "HAL_device.h"


enum
{
#ifdef BSP_USING_SPI1
    SPI1_INDEX,
#endif
#ifdef BSP_USING_SPI2
    SPI2_INDEX,
#endif
#ifdef BSP_USING_SPI3
    SPI3_INDEX,
#endif
#ifdef BSP_USING_SPI4
    SPI4_INDEX,
#endif
};

static struct tk499_spi_config spi_config[] =
{
#ifdef BSP_USING_SPI1
    SPI1_BUS_CONFIG,
#endif

#ifdef BSP_USING_SPI2
    SPI2_BUS_CONFIG,
#endif

#ifdef BSP_USING_SPI3
    SPI3_BUS_CONFIG,
#endif

#ifdef BSP_USING_SPI4
    SPI4_BUS_CONFIG,
#endif
};

static struct tk499_spi spi_bus_obj[sizeof(spi_config) / sizeof(spi_config[0])] = {0};

rt_err_t tk499_spi_init(struct tk499_spi *spi_drv, struct rt_spi_configuration *cfg)
{
    SPI_HandleTypeDef *spi_handle = &spi_drv->handle;

    RT_ASSERT(spi_drv != RT_NULL);
    RT_ASSERT(cfg != RT_NULL);

    if(cfg->mode & RT_SPI_SLAVE)
    {
        spi_handle->Init.SPI_Mode = SPI_Mode_Slave;
    }
    else
    {
        spi_handle->Init.SPI_Mode = SPI_Mode_Master;
    }

    spi_handle->Init.SPI_DataSize = SPI_DataSize_8b;

    if(cfg->data_width == 8)
    {
        spi_handle->Init.SPI_DataWidth = SPI_DataWidth_8b;
    }
    else
    {
        spi_handle->Init.SPI_DataWidth = SPI_DataWidth_7b;
    }
    
    if (cfg->mode & RT_SPI_CPOL)
    {
        spi_handle->Init.SPI_CPOL = SPI_CPOL_High;
    }
    else
    {
        spi_handle->Init.SPI_CPOL = SPI_CPOL_Low;
    }

    if (cfg->mode & RT_SPI_CPHA)
    {
        spi_handle->Init.SPI_CPHA = SPI_CPHA_2Edge;
    }
    else
    {
        spi_handle->Init.SPI_CPHA = SPI_CPHA_1Edge;
    }
    
    if (cfg->mode & RT_SPI_NO_CS)
    {
        spi_handle->Init.SPI_NSS = SPI_NSS_Hard;
    }
    else
    {
        spi_handle->Init.SPI_NSS = SPI_NSS_Soft;
    }

    spi_handle->Init.SPI_BaudRatePrescaler = 16;

    if (cfg->mode & RT_SPI_MSB)
    {
        spi_handle->Init.SPI_FirstBit = SPI_FirstBit_MSB;
    }
    else
    {
        spi_handle->Init.SPI_FirstBit = SPI_FirstBit_LSB;
    }
    
	SPI_Init(spi_handle->Instance, &spi_handle->Init);

	SPI_Cmd(spi_handle->Instance, ENABLE);
    SPI_BiDirectionalLineConfig(spi_handle->Instance, SPI_Direction_Tx);
    SPI_BiDirectionalLineConfig(spi_handle->Instance, SPI_Direction_Rx);

    return RT_EOK;
}

static rt_uint8_t spi_read_write_byte(SPI_TypeDef* SPIx, rt_uint8_t data)
{
    SPI_SendData(SPIx, data);
    while (1)
    {
        if(SPI_GetFlagStatus(SPIx, SPI_FLAG_RXAVL))	
        {
            return SPI_ReceiveData(SPIx);
        }
        
    }
}

static rt_uint32_t spixfer(struct rt_spi_device *device, struct rt_spi_message *message)
{
    struct tk499_spi *spi_drv =  rt_container_of(device->bus, struct tk499_spi, spi_bus);
    SPI_HandleTypeDef *spi_handle = &spi_drv->handle;
    struct tk499_hw_spi_cs *cs = device->parent.user_data;
	
    RT_ASSERT(device != RT_NULL);
    RT_ASSERT(device->bus != RT_NULL);
    RT_ASSERT(device->bus->parent.user_data != RT_NULL);
    RT_ASSERT(message != RT_NULL);

    if(message->cs_take)
    {
        GPIO_WriteBit(cs->GPIOx, cs->GPIO_Pin, Bit_RESET);
    }
    
    const rt_uint8_t *send_ptr = message->send_buf;
    rt_uint8_t *recv_ptr = message->recv_buf;
    rt_size_t size = message->length;

    while(size--)
    {
        rt_uint8_t data = 0xFF;

        if(send_ptr != RT_NULL && recv_ptr != RT_NULL)
        {
            data = *send_ptr++;
            *recv_ptr = spi_read_write_byte(spi_handle->Instance, data);
            recv_ptr++;
		}
        else if(send_ptr != RT_NULL)
        {
            data = *send_ptr++;
            spi_read_write_byte(spi_handle->Instance, data);
        }
        else if(recv_ptr != RT_NULL)
        {
            *recv_ptr = spi_read_write_byte(spi_handle->Instance, data);
            *recv_ptr++;
        }
    }
    
    if(message->cs_release)
    {
        GPIO_WriteBit(cs->GPIOx, cs->GPIO_Pin, Bit_SET);
    }

    return message->length;
}

static rt_err_t spi_configure(struct rt_spi_device *device,
                              struct rt_spi_configuration *configuration)
{
    struct tk499_spi *spi_drv = RT_NULL;
    RT_ASSERT(device != RT_NULL);
    RT_ASSERT(configuration != RT_NULL);

    spi_drv =  rt_container_of(device->bus, struct tk499_spi, spi_bus);
    spi_drv->cfg = configuration;

    return tk499_spi_init(spi_drv, configuration);
}

static const struct rt_spi_ops stm_spi_ops =
{
    .configure = spi_configure,
    .xfer = spixfer,
};

static int rt_hw_spi_bus_init(void)
{
    GPIO_InitTypeDef  GPIO_InitStructure;
    rt_err_t result;
	int i;
	
    for (i = 0; i < sizeof(spi_config) / sizeof(spi_config[0]); i++)
    {
        RCC_APB2PeriphClockCmd(spi_config[i].RCC_APB2Periph, ENABLE);

        GPIO_InitStructure.GPIO_Pin  = spi_config[i].CLK_GPIO_Pin | spi_config[i].MOSI_GPIO_Pin;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
        GPIO_Init(GPIOA, &GPIO_InitStructure);
        
        GPIO_InitStructure.GPIO_Pin  = spi_config[i].MISO_GPIO_Pin;
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
        GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; 
        GPIO_Init(spi_config[i].GPIOx, &GPIO_InitStructure);

        GPIO_PinAFConfig(spi_config[i].GPIOx, spi_config[i].CLK_GPIO_Pin | spi_config[i].MOSI_GPIO_Pin | spi_config[i].MISO_GPIO_Pin, GPIO_AF_SPI);

        spi_bus_obj[i].config = &spi_config[i];
        spi_bus_obj[i].spi_bus.parent.user_data = &spi_config[i];
        spi_bus_obj[i].handle.Instance = spi_config[i].Instance;

        result = rt_spi_bus_register(&spi_bus_obj[i].spi_bus, spi_config[i].bus_name, &stm_spi_ops);
        RT_ASSERT(result == RT_EOK);

        rt_kprintf("%s bus init done\n", spi_config[i].bus_name);
    }

    return result;
}

/**
  * Attach the spi device to SPI bus, this function must be used after initialization.
  */
rt_err_t rt_hw_spi_device_attach(const char *bus_name, const char *device_name, GPIO_TypeDef *cs_gpiox, uint16_t cs_gpio_pin)
{
    rt_err_t result;
    struct rt_spi_device *spi_device;
    struct tk499_hw_spi_cs *cs_pin;

    /* initialize the cs pin && select the slave*/
    GPIO_InitTypeDef GPIO_Initure;

    RT_ASSERT(bus_name != RT_NULL);
    RT_ASSERT(device_name != RT_NULL);

    GPIO_Initure.GPIO_Pin = cs_gpio_pin;
    GPIO_Initure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Initure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(cs_gpiox, &GPIO_Initure);
    GPIO_WriteBit(cs_gpiox, cs_gpio_pin, Bit_SET);

    /* attach the device to spi bus*/
    spi_device = (struct rt_spi_device *)rt_malloc(sizeof(struct rt_spi_device));
    RT_ASSERT(spi_device != RT_NULL);
    cs_pin = (struct tk499_hw_spi_cs *)rt_malloc(sizeof(struct tk499_hw_spi_cs));
    RT_ASSERT(cs_pin != RT_NULL);
    cs_pin->GPIOx = cs_gpiox;
    cs_pin->GPIO_Pin = cs_gpio_pin;

    result = rt_spi_bus_attach_device(spi_device, device_name, bus_name, (void *)cs_pin);

    if (result != RT_EOK)
    {
        rt_kprintf("%s attach to %s faild, %d\n", device_name, bus_name, result);
    }

    RT_ASSERT(result == RT_EOK);

    rt_kprintf("%s attach to %s done\n", device_name, bus_name);

    return result;
}

static void stm32_get_dma_info(void)
{
    return ;
}

int rt_hw_spi_init(void)
{
    stm32_get_dma_info();
    return rt_hw_spi_bus_init();
}
INIT_BOARD_EXPORT(rt_hw_spi_init);

#endif /* BSP_USING_SPI1 || BSP_USING_SPI2 || BSP_USING_SPI3 || BSP_USING_SPI4 || BSP_USING_SPI5 */
#endif /* RT_USING_SPI */
